/*
 * Copyright 2016 Stuart Kent
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.example.mybugshaker.flow.email;

import com.example.mybugshaker.utils.Logger;
import io.reactivex.annotations.NonNull;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public final class EmailCapabilitiesProvider {
    private static final String[] DUMMY_EMAIL_ADDRESSES = new String[] {"someone@example.com"};
    private static final String DUMMY_EMAIL_SUBJECT_LINE = "Any Subject Line";
    private static final String DUMMY_EMAIL_BODY = "Any Body";
    private static final Uri DUMMY_EMAIL_URI = Uri.EMPTY_URI;

    @NotNull
    private final IBundleManager iBundleManager;

    @NotNull
    private final GenericEmailIntentProvider genericEmailIntentProvider;

    @NotNull
    private final Logger logger;
    private final Context fcontext;

    public EmailCapabilitiesProvider(
            Context context,
            @NotNull final IBundleManager bundleManager,
            @NotNull final GenericEmailIntentProvider fgenericEmailIntentProvider,
            @NotNull final Logger flogger) {
        this.fcontext=context;
        this.iBundleManager = bundleManager;
        this.genericEmailIntentProvider = fgenericEmailIntentProvider;
        this.logger = flogger;
    }

    public boolean canSendEmails() throws RemoteException {
        logger.d("Checking for email apps...");

        final List<AbilityInfo> emailAppInfoList = getEmailAppList();
        if (emailAppInfoList == null || emailAppInfoList.isEmpty()) {
            logger.d("No email apps found.");
            return false;
        }
        logEmailAppNames("Available email apps: ", emailAppInfoList);
        return true;
    }

    /* default */ boolean canSendEmailsWithAttachments() throws RemoteException {
        logger.d("Checking for email apps that can send attachments...");

        final List<AbilityInfo> emailAppInfoList = getEmailWithAttachmentAppList();

        if (emailAppInfoList.isEmpty()) {
            logger.d("No email apps can send attachments.");
            return false;
        }

        logEmailAppNames("Available email apps that can send attachments: ", emailAppInfoList);
        return true;
    }

    @NotNull
    private List<AbilityInfo> getEmailAppList() throws RemoteException {
        final Intent queryIntent = genericEmailIntentProvider.getEmailIntent(DUMMY_EMAIL_ADDRESSES,DUMMY_EMAIL_SUBJECT_LINE,DUMMY_EMAIL_BODY);
        return iBundleManager.queryAbilityByIntent(
                queryIntent, queryIntent.FLAG_NOT_OHOS_COMPONENT,-1);
    }

    @NotNull
    private List<AbilityInfo> getEmailWithAttachmentAppList() throws RemoteException {
        final Intent queryIntent = genericEmailIntentProvider.getEmailWithAttachmentIntent(
                DUMMY_EMAIL_ADDRESSES, DUMMY_EMAIL_SUBJECT_LINE, DUMMY_EMAIL_BODY, DUMMY_EMAIL_URI);
        return iBundleManager.queryAbilityByIntent(
                queryIntent, queryIntent.FLAG_NOT_OHOS_COMPONENT,-1);
    }

    private void logEmailAppNames(
            @NotNull final String prefix,
            @NotNull final List<AbilityInfo> emailAppInfoList) {

        final List<CharSequence> emailAppNames = new ArrayList<>();
        for (final AbilityInfo emailAppInfo: emailAppInfoList) {
            emailAppNames.add(emailAppInfo.getLabel());
        }

        final String emailAppInfoString = EmailCapabilitiesProvider.join(",",emailAppNames);
        logger.d(prefix + emailAppInfoString);
    }
    public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) {
        final Iterator<?> it = tokens.iterator();
        if (!it.hasNext()) {
            return "";
        }
        final StringBuilder sb = new StringBuilder();
        sb.append(it.next());
        while (it.hasNext()) {
            sb.append(delimiter);
            sb.append(it.next());
        }
        return sb.toString();
    }
}
